﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace SSRSViewer
{
    partial class SingleValidValueUserControl : UserControl, IParameterEditor
    {
        public SingleValidValueUserControl()
        {
            InitializeComponent();
        }
        public RdlDataProvider DataProvider { get; set; }
        public SqlConnection Connection { get; set; }
        public RdlValidValuesParser ValuesParser { get; set; }

        public void Initialize()
        {
            if (DataProvider == null)
                throw new NullReferenceException("Dataprovider was not assigned.");
            if (Connection == null)
                throw new NullReferenceException("Sql Connection was not assigned.");

            SqlCommand cmd = new SqlCommand(DataProvider.CommandText, Connection);
            SqlDataReader reader;

            if (Connection.State != ConnectionState.Open)
                Connection.Open();

            List<CheckboxItem> items = new List<CheckboxItem>();

            reader = cmd.ExecuteReader();

            while (reader.Read())
                items.Add(new CheckboxItem()
                {
                    Key = reader.GetValue(reader.GetOrdinal(ValuesParser.LabelField)).ToString(),
                    Value = reader.GetValue(reader.GetOrdinal(ValuesParser.ValueField))
                });
            Connection.Close();

            this.checkboxItemBindingSource.DataSource = items;

            this.comboBox1.SelectedIndex = -1;
        }

        #region IParameterEditor Members

        public object EditValue
        {
            get
            {
                if (comboBox1.SelectedItem != null)
                    return (comboBox1.SelectedItem as CheckboxItem).Value;
                else
                    return null;
            }
            set 
            {
                comboBox1.SelectedItem = comboBox1.Items.Cast<CheckboxItem>().Where(item => item.Value == value).SingleOrDefault();
            }
        }

        public string Prompt
        {
            get { return lbPrompt.Text; }
            set { lbPrompt.Text = value; }
        }
        public RdlReportParameter EditingParameter { get; set; }

        #endregion
    }
}
